<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Good;
use App\Models\GoodAttribute;
use App\Models\GoodInfo;
use App\Models\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class GoodInfoController extends Controller
{
    public function all(Request $request, $goodId)
    {
        if (!$this->checkGood($goodId)) {
            return jsonResponse(40000);
        }
        $items = GoodInfo::where('good_id', $goodId)->get();
        return jsonResponse(config('common.successCode'), $items);
    }

    /**
     * 批量创建商品：传入商品ID，根据ID获取商品属性，将属性组合形成商品
     * @param $goodId
     * @return array
     */
    public function batchCreate($goodId)
    {
        if (!$this->checkGood($goodId)) {
            return jsonResponse(40000);
        }

        // 清空已有的商品属性组合
        GoodInfo::where('good_id', $goodId)->delete();

        $attributes = GoodAttribute::where('good_id', $goodId)->get();
        $items = [];
        foreach ($attributes as $attribute) {
            $flag = true;
            foreach ($items as $k => $item) {
                if ($k == $attribute['attr_id']) {
                    $flag = false;
                    $item[] = $attribute['id'];
                    break;
                }
            }
            if ($flag) {
                $items[$attribute['attr_id']] = [$attribute['id']];
            }
        }
        $results = [];
        foreach ($items as $k => $v) {
            $results[] = $v;
        }
        $this->generateGoods($results);
        foreach ($results[0] as $result) {
            $info = new GoodInfo();
            $info['uid'] = $result;
            $info->save();
        }
        return jsonResponse();
    }

    public function create(Request $request, $goodId)
    {
        if (!$this->checkGood($goodId)) {
            return jsonResponse(40000);
        }

        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $uid = $request->get('uid');
        $uids = explode(config('common.delimiter'), $uid);
        $attributes = [];
        foreach ($uids as $uid) {
            $goodAttr = GoodAttribute::find($uid);
            if (empty($goodAttr)) {
                return jsonResponse(40000);
            }
            $attributes[] = $goodAttr;
        }

        $info = GoodInfo::where('uid', $uid)->first();
        if (empty($info)) {
            $info = new GoodInfo();
        }
        $number = $request->get('number');
        $info['uid'] = $uid;
        $info['number'] = $number;
        $info['price'] = $request->get('price');
        if ($number != -1) {
            $warnNumber = $request->get('warn_number', 0);
            if ($warnNumber >= $number) {
                return jsonResponse(41303);
            }
            $info['warn_number'] = $warnNumber;
        } else {
            $info['warn_number'] = -1;
        }
        $info['avatar'] = $request->get('avatar');
        $images = $request->get('images');
        foreach ($images as $image) {
            $file = Image::find($image);
            if (empty($file)) {
                return jsonResponse(40000);
            }
        }
        $info['images'] = implode(config('common.delimiter'), $images);
        $info['is_on_sale'] = $request->get('is_on_sale');
        $info->save();
        return jsonResponse();
    }

    public function update(Request $request, $goodId, $id)
    {
        if (!$this->checkGood($goodId)) {
            return jsonResponse(40000);
        }

        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $uid = $request->get('uid');
        $uids = explode(config('common.delimiter'), $uid);
        $attributes = [];
        foreach ($uids as $uid) {
            $goodAttr = GoodAttribute::find($uid);
            if (empty($goodAttr)) {
                return jsonResponse(40000);
            }
            $attributes[] = $goodAttr;
        }

        $info = GoodInfo::find($id);
        if (empty($info)) {
            return jsonResponse(40000);
        }
        $number = $request->get('number');
        $info['uid'] = $uid;
        $info['number'] = $number;
        $info['price'] = $request->get('price');
        if ($number != -1) {
            $warnNumber = $request->get('warn_number', 0);
            if ($warnNumber >= $number) {
                return jsonResponse(41303);
            }
            $info['warn_number'] = $warnNumber;
        } else {
            $info['warn_number'] = -1;
        }
        $info['avatar'] = $request->get('avatar');
        $images = $request->get('images');
        foreach ($images as $image) {
            $file = Image::find($image);
            if (empty($file)) {
                return jsonResponse(40000);
            }
        }
        $info['images'] = implode(config('common.delimiter'), $images);
        $info['is_on_sale'] = $request->get('is_on_sale');
        $info->save();
        return jsonResponse();
    }

    public function destroy($id)
    {
        GoodInfo::destroy($id);
        return jsonResponse();
    }

    public function test()
    {
        $items = [
            [1, 2, 3],
            ['a', 'b', 'c'],
            ['我', '你']
        ];
        $this->generateGoods($items);
        return $items[0];
    }

    private function checkGood($id)
    {
        $good = Good::find($id);
        if (empty($good)) {
            return false;
        }
        return true;
    }

    private function validate($request)
    {
        return Validator::make($request->all(), [
            'uid' => 'required',
            'number' => 'required|integer|min:-1',
            'price' => 'required|numeric|min:0',
            'avatar' => 'exists:images,id',
            'images' => 'array',
        ], [
            'uid.required' => 'UID不能为空',
            'number.required' => '数量不合法',
            'number.integer' => '数量不合法',
            'number.min' => '数量不合法',
            'price.required' => '价格不合法',
            'price.numeric' => '价格不合法',
            'price.min' => '价格不合法',
            'avatar.exists' => '主图不存在',
            'images.array' => 'images需为数组',
        ]);
    }

    /**
     * 递归组合商品，形成商品的uid
     * @param $items
     * @return bool
     */
    private function generateGoods(&$items) {
        $num = count($items);
        if ($num == 0) {
            return false;
        }
        if ($num == 1) {
            return false;
        }
        $results = [];
        foreach ($items[0] as $first) {
            foreach ($items[1] as $second) {
                $results[] = $first . config('common.delimiter') . $second;
            }
        }
        array_splice($items, 0, 1);
        $items[0] = $results;
        $this->generateGoods($items);
    }
}
